---
--类名: MapUpdate.lua
--创建日期: 2018-1-12
--创建人: 陈小虎
--功能描述: 
--修改内容：
--修改日期:   
--修改人:     
--修改备注: 

local Entity = import(".Entity")

local MapUpdate = class("MapUpdate")

function MapUpdate:ctor()
	cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

	self.uuid = 0
	self.mapId = 0
	self.myEntity = Entity.new()
	self.otherEntities = {}
end

function MapUpdate:read(pbData)
	-- dump(pbData, "MapUpdate:read")

	self.uuid = pbData.uuid
	self.mapId = pbData.mapId
	-- print("---- self.uuid = ",self.uuid)
	-- print("---- self.mapId = ",self.mapId)

	self.myEntity:read(pbData.self)

	local newOtherEntities = {}
	if pbData.entities then
		for _,v in ipairs(pbData.entities) do
			local entity = self.otherEntities[v.id] or Entity.new()
			entity:read(v)
			-- entity.info出于节省客户端流量考虑，需要客户端进行缓存
			newOtherEntities[v.id] = entity
		end

	end

	-- 如果有队伍且有机器人，加上队伍的机器人entity
	local team = app:sendMsg("TeamModel", "getTeam")
	if team and team:getRobotNum() > 0 then
		local leaderUid = team:getLeaderUid()
		local leaderEntity = newOtherEntities[leaderUid]
		leaderEntity = leaderEntity or self.myEntity
		if leaderEntity then
			local robots = team:getRobots()
			for i,robot in ipairs(robots) do
				local uid = robot:getUid()
				local entity = self.otherEntities[uid]
				if entity then
					entity.leader = leaderEntity.id
					entity.faceTo = leaderEntity.faceTo
					entity.status = leaderEntity.status
					entity.behavior = leaderEntity.behavior
				else
					local entityVo = {}
					entityVo.id = uid
					entityVo.leader = leaderEntity.id
					entityVo.faceTo = leaderEntity.faceTo
					entityVo.status = leaderEntity.status
					entityVo.posX = leaderEntity.posX
					entityVo.behavior = leaderEntity.behavior
					entityVo.info = robot:getBaseInfoParams()

					entity = Entity.new()
					entity:read(entityVo)
				end
				newOtherEntities[uid] = entity
			end
		end 
	end

	self.otherEntities = newOtherEntities

	-- dump(newOtherEntities, "newOtherEntities")
end

function MapUpdate:getMapId()
	return self.mapId
end

function MapUpdate:isThisMap(mapId)
	return (self.mapId == mapId) and true or false
end

function MapUpdate:getSelf()
	return self.myEntity
end

function MapUpdate:getOtherEntities()
	return self.otherEntities
end

function MapUpdate:getOtherEntityById(id)
	return self.otherEntities and self.otherEntities[id] or nil
end

return MapUpdate
